package cn.iocoder.yudao.module.promotion.gift.mq;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.iocoder.yudao.module.api.trade.scan.dto.ScanOrderDTO;
import cn.iocoder.yudao.module.api.trade.scan.message.ScanOrderPaidMessage;
import cn.iocoder.yudao.module.promotion.gift.service.core.CoreGiftRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 引流赠品 事件消费者
 *
 * @author 山野羡民
 */
@Component
@Slf4j
public class GiftConsumer {

    @EventListener
    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(ScanOrderPaidMessage message) {
        ScanOrderDTO order = message.getOrder();
        log.info("[promotion/gift][onMessage][线下扫码订单支付完成事件({})]", order.getTradeNo());
        if (CollUtil.isNotEmpty(order.getGiftActivityIds())) {
            // 扫码订单携带有赠品活动编号，说明需要发放赠品
            if (order.getUserId() == null || order.getUserId() <= 0) {
                log.warn("[promotion/gift][onMessage][线下扫码订单支付完成事件，订单对应的用户编号不存在，疑似未登录的情况下付款，忽略赠品的发放]");
                return;
            }
            SpringUtil.getBean(CoreGiftRecordService.class).pending(order.getUserId(), order.getTradeNo(), order.getGiftActivityIds());
        }
    }

}
